from pylons import Response, c, g, cache, request, session
from pylons.controllers import WSGIController
from pylons.decorators import jsonify, validate
from pylons.templating import render
from pylons.helpers import abort, redirect_to, etag_cache
from pylons.i18n import N_, _, ungettext
#from authkit.pylons_adaptors import authorize
from bumblebee.lib.auth import authorize, get_user, redirect_to_login, \
                               SignedIn, InGroup, HasPermission, NotAuthorized
from bumblebee.lib.helpers import get_object_or_404
from bumblebee.model import forms
import bumblebee.model as model
import bumblebee.lib.helpers as h

class BaseController(WSGIController):

    def __call__(self, environ, start_response):
        # Refresh database session
        model.resync()
        # Add current user to template
        c.current_user = get_user()
        # Get flash message
        c.flash = session.pop('flash', '')
        if c.flash:
            session.save()
        # Check if __permission__ set
        # Insert any code to be run per request here. The Routes match
        # is under environ['pylons.routes_dict'] should you want to check
        # the action or route vars here
        return WSGIController.__call__(self, environ, start_response)

class SecureController(BaseController):
    __permission__ = SignedIn()

    def __before__(self):
        self._authorize()

    def _authorize(self):
        "Do permission check on all controller actions.Use @authorize decorator for individual actions"
        if self.__permission__:
            try:
                self.__permission__.check()
            except NotAuthorized:
                redirect_to_login()

# Include the '_' function in the public names
__all__ = [__name for __name in locals().keys() if not __name.startswith('_') \
           or __name == '_']
